$(document).ready(function(){
	var ctx =$("#ctx").val();
	/***************************    广告位列表页    ***************************/

	//获取尺寸
	if($("#size").val() == 0 || $("#size").val() == ""){
		$("#selectBar_size a:first").addClass("selectBar_change");
	}
	$("#selectBar_size a").each(function(){
 		var value = $(this).attr("value");
 		if($("#size").val() == value){
 			$(this).addClass("selectBar_change").siblings('.selectBar_change').removeClass('selectBar_change');
 		}
 	});
	$("#selectBar_size a").click(function(){
		$("#size").val($(this).attr("value"));
		if($(this).attr("value") != ""){
			var _size = $(this).attr("value").split('X',2);
			$("#width").val(_size[0]);
			$("#height").val(_size[1]);
		}else{
			$("#width").val("");
			$("#height").val("");
		}
 		refreshData();
 	});
	
	//取消垫底广告
	$("#deletUrl").click(function(){
		$("#uploadfilehidden").val("");
		$("#smallImg").val("");
		$("#default_path_small").val("");
		$("#pictureName").val("");
		$("#default_url").val("");
		$(".ace-file-input span").attr("data-title","");
 	});
	
	//类型
 	if($("#device").val() == -1 || $("#device").val() == ""){
 		$("#selectBar_type a:first").addClass("selectBar_change");
	}
 	$("#selectBar_type a").each(function(){
 		var value = $(this).attr("value");
 		if($("#device").val() == value){
 			$(this).addClass("selectBar_change").siblings('.selectBar_change').removeClass('selectBar_change');
 		}
 	});
 	$("#selectBar_type a").click(function(){
 		$("#device").val($(this).attr("value"));
 		refreshData();
 	});
 	
 	var operatorJs = $("#operatorJs").val();
 	if(operatorJs != 1){
 		$('#keywordDivCreate').css("display","none");
 	}
 	var zoneJs = $('#zoneJs').val();
 	if(zoneJs != 1){
 		$('#keywordDivEdit').css("display","none");
 	}
 	//获取创意尺寸
	if($("#position").val() == -1 || $("#position").val() == ""){
		$("#selectBar_position a:first").addClass("selectBar_change");
	}
	$("#selectBar_position a").each(function(){
 		var value = $(this).attr("value");
 		if($("#position").val() == value){
 			$(this).addClass("selectBar_change").siblings('.selectBar_change').removeClass('selectBar_change');
 		}
 	});
	$("#selectBar_position a").click(function(){
		$("#position").val($(this).attr("value"));
 		refreshData();
 	});
	
 	//状态全部、开启、停用
 	if($("#status").val() == -1 || $("#status").val() == ""){
 		$("#selectBar_status a:first").addClass("selectBar_change");
	}
 	$("#selectBar_status a").each(function(){
 		var value = $(this).attr("value");
 		if($("#status").val() == value){
 			$(this).addClass("selectBar_change").siblings('.selectBar_change').removeClass('selectBar_change');
 		}
 	});
 	$("#selectBar_status a").click(function(){
 		$("#status").val($(this).attr("value"));
 		refreshData();
 	});
 
	//开启,暂停
	$("#btn-enable,#btn-disable,#btn-delete").click(function(){
		if($(this).attr("id") == "btn-enable"){
			url = "zone/enable";
		}else if($(this).attr("id") == "btn-disable"){
			url = "zone/disable";
		}else if($(this).attr("id") == "btn-delete"){
			url = "zone/delete";
		}
		singleOper($(this),url);
	});
			
	//批量开启,批量暂停
	$("#all-btn-enable,#all-btn-disable,#all-btn-delete").click(function(){
		if($(this).attr("id") == "all-btn-enable"){
			url = "zone/enable";
		}else if($(this).attr("id") == "all-btn-disable"){
			url = "zone/disable";
		}else if($(this).attr("id") == "all-btn-delete"){
			url = "zone/delete";
		}
		batchOpear($(this),url);
	});
	
	//取代码
	$("#btn-getcode,#btn-getcode2").click(function(){
		var zoneId = $(this).attr("value");
		var url = "zone/getCode?zoneId="+zoneId;
		$.getJSON(url, function(data) {
			var data_1 = data;
			$('.bootbox-body').text(data_1);
		});
		bootbox.dialog({
			message:"代码为：",
			title: "该广告位的代码",
			locale: 'zh_CN',
			buttons: {
				success: {
					label: "复制",
					className: "btn-success",
					callback: function() {
						var _content = $('.bootbox-body').text();
					}
				},
				main: {
					label: "关闭",
					className: "btn-primary",
					callback: function() {
					}
				}
			}
		});
		//以下代码实现复制功能，利用ZeroClipboard插件实现
		var client = new ZeroClipboard($('.modal-footer .btn-success'));
		client.on('ready', function(event) {
			// console.log( 'movie is loaded' );
			client.on('copy', function(event) {
				event.clipboardData.setData('text/plain', $('.bootbox-body').text());
			});
			client.on('aftercopy', function(event) {
				console.log('Copied text to clipboard: ' + event.data['text/plain']);
			});
		});
		client.on('error', function(event) {
			// console.log( 'ZeroClipboard error of type "' + event.name + '": ' + event.message );
			ZeroClipboard.destroy();
		});
	});
	
	//取代码统计
	$("#btn-getcode3,#btn-getcode4").click(function(){
		var zoneId = $(this).attr("value");
		var url = "zone/getCodeStatistics?zoneId="+zoneId;
		$.getJSON(url, function(data) {
			var data_1 = data;
			$('.bootbox-body').text(data_1);
		});
		bootbox.dialog({
			message:"代码为：",
			title: "该广告位PV的代码",
			locale: 'zh_CN',
			buttons: {
				success: {
					label: "复制",
					className: "btn-success",
					callback: function() {
						var _content = $('.bootbox-body').text();
					}
				},
				main: {
					label: "关闭",
					className: "btn-primary",
					callback: function() {
					}
				}
			}
		});
		//以下代码实现复制功能，利用ZeroClipboard插件实现
		var client = new ZeroClipboard($('.modal-footer .btn-success'));
		client.on('ready', function(event) {
			// console.log( 'movie is loaded' );
			client.on('copy', function(event) {
				event.clipboardData.setData('text/plain', $('.bootbox-body').text());
			});
			client.on('aftercopy', function(event) {
				console.log('Copied text to clipboard: ' + event.data['text/plain']);
			});
		});
		client.on('error', function(event) {
			// console.log( 'ZeroClipboard error of type "' + event.name + '": ' + event.message );
			ZeroClipboard.destroy();
		});
	});
	//取JS代码
	$(".btn-getcode5").click(function(){
		
		var zoneId = $(this).attr("value");
		var url = "zone/getJsCode?zoneId="+zoneId;
		$.getJSON(url, function(data) {
			var data_1 = data;
			var data_2 = '<script src="'+data_1+'" language="JavaScript"></script>';
			$('.bootbox-body').text(data_2);
		});
		bootbox.dialog({
			message:"代码为：",
			title: "该广告位的JS代码",
			locale: 'zh_CN',
			buttons: {
				success: {
					label: "复制",
					className: "btn-success",
					callback: function() {
						var _content = $('.bootbox-body').text();
					}
				},
				main: {
					label: "关闭",
					className: "btn-primary",
					callback: function() {
					}
				}
			}
		});
		//以下代码实现复制功能，利用ZeroClipboard插件实现
		var client = new ZeroClipboard($('.modal-footer .btn-success'));
		client.on('ready', function(event) {
			// console.log( 'movie is loaded' );
			client.on('copy', function(event) {
				event.clipboardData.setData('text/plain', $('.bootbox-body').text());
			});
			client.on('aftercopy', function(event) {
				console.log('Copied text to clipboard: ' + event.data['text/plain']);
			});
		});
		client.on('error', function(event) {
			// console.log( 'ZeroClipboard error of type "' + event.name + '": ' + event.message );
			ZeroClipboard.destroy();
		});
	});
	
	/***************************    创建，编辑广告主    ***************************/
	
	//初始化加载上传控件
	if($("#filepicture_picture").html()){
		if($("#uploadfilehidden").val() !=""){
			$("#imgDivs").css("display","block");
			$("#deletUrl").css("display","inline-block");
		}else{
		 	$("#imgDivs").css("display","none");
		 	$("#deletUrl").css("display","none");
		}
		initFile($("#uploadfile"),$("#pictureName").val());
		$('#uploadfilestr').unbind('click').click(function() {
	 		getUploadFile();
		});
	}
	
	 //选中右移
	$("#all_industry li").live("click",function() {
		var obj = $(this);
		$("#industryFatherName").val(this.innerHTML);
		$.post('../../isExistIndustry',{fatherId:$(this).attr("value")},function(data){
			if(data == false){
				layer.open({
				    type: 2,
					title: '选择行业',
					shadeClose: false,
					shade: 0.6,
					fix:false,
					area: ['685px','430px'],
					content: ['../../getIndustry?fatherId='+obj.attr("value")]
				});
				return false;
			}else{
				var industryId = obj.attr("value");
				$("#blacklist").append("<li value='"+industryId+"' title='"+obj.text()+"-"+obj.text()+"'><span id='industryName'>" + obj.text() + "</span><input type='button' class='movedel'/></li>");
				if($("#industry_blacklist").val() == ""){
					$("#industry_blacklist").val(industryId);//父层的元素
				}else {
					$("#industry_blacklist").val($("#industry_blacklist").val()+","+industryId);//父层的元素
				}
				return false;
			}
		});
	});
	
	  //选中左移
	$('#blacklist li input.movedel').live("click",function() {
		var mychoice = $(this).parents("li").text();
		var mychoicevalue = $(this).parents("li").attr("value");
		$(this).parents("li").remove();
		//左移黑名单删除传值
		var industryArr = $("#industry_blacklist").val().split(",");
		for(var i=0;i<industryArr.length;i++){
			if(industryArr[i] == mychoicevalue){
				industryArr.splice(i,1);
			}
		} 
		if(industryArr != 0){
			for(var j=0;j<industryArr.length;j++){
				if(j == 0){
					$("#industry_blacklist").val(industryArr[0]);
				}else{
					$("#industry_blacklist").val($("#industry_blacklist").val()+","+industryArr[j]);
				}
			} 
		}else{
			$("#industry_blacklist").val("");
		}
	});


	//添加全部
	$('#add_all').live("click",function() {
		var url = "../../getAllIndustry";
		var ul = document.getElementById("blacklist");
		var industryId = "";
		var list = $("#industry_blacklist").val();
		$.getJSON( url, function(data) {
			$.each( data, function( key, val ) {
				if(list.indexOf(val.id) == -1){
					industryId += val.id+",";
				}
				$(ul).append("<li value='"+val.id+"' title='"+val.fatherName+"-"+val.name+"'><span id='industryName'>" + val.name + "</span><input type='button' class='movedel'/></li>");
			});
		});
		if(industryId != ""){
			industryId = industryId.substring(0, industryId.length-1);
			if(list == ""){
				$("#industry_blacklist").val(industryId);
			}else {
				$("#industry_blacklist").val(list+","+industryId);
			}
		}
	});	
	
	//清空全部
	$('#clear_all').live("click",function() {
		var lis = $('#blacklist li');		
		var len = lis.length;		
		for(var i=0; i<len;i++){			
			lis[i].remove();
		}
   	    $("#industry_blacklist").val("");
		//传值同步清空
		 // document.getElementById("industry_blacklist").value ="";		
	});	
	
	//网站添加黑名单
	var web_blackname = "";
	var glo_web_blacklist = $('#web_blacklist li');
	for(var counts=0;counts<glo_web_blacklist.length;counts++){
      if(web_blackname){
	   web_blackname = web_blackname +"," + $(glo_web_blacklist[counts]).text();
	  }else{
	  	web_blackname =$(glo_web_blacklist[counts]).text();
	   }
	}
	$("#add_web").live("click",function() {
		var blackname=$('#blackname').val();
		if(blackname == ""){
			bootbox.alert("请输入要添加的网站黑名单！");
			return false;
		}	
		var blacknameArr = $("#web_blacklistvalue").val().split(",");
		if($.inArray(blackname, blacknameArr) != -1){  
			bootbox.alert("您输入的网站黑名单已存在！");
			return false;
		}  
		var ul = document.getElementById("web_blacklist");
		$(ul).append("<li>" + blackname + "<input type='button' class='movedel'/></li>");	
		$('#blackname').val("");
		//黑名单传值
		if($("#web_blacklistvalue").val() == ""){
			$("#web_blacklistvalue").val(blackname);
		}else{
			$("#web_blacklistvalue").val($("#web_blacklistvalue").val()+","+blackname);
		}
	});
	//删除黑名单
	$('#web_blacklist li input.movedel').live("click",function() {		
		$(this).parents("li").remove(); 
		var mychoice = $(this).parents("li").text();
		var blacknameArr = $("#web_blacklistvalue").val().split(",");
		for(var i=0;i<blacknameArr.length;i++){
			if(blacknameArr[i] == mychoice){
				blacknameArr.splice(i,1);
			}
		} 
		//左移黑名单删除传值
		if(blacknameArr.length !=0){
			for(var j=0;j<blacknameArr.length;j++){
				if(j == 0){
					$("#web_blacklistvalue").val(blacknameArr[0]);
				}else{
					$("#web_blacklistvalue").val($("#web_blacklistvalue").val()+","+blacknameArr[j]);
				}
			} 
		}else{
			$("#web_blacklistvalue").val("");
		}
		
	});
	
	//清空黑名单
	$("#clear_allweb").live("click",function() {
		var lis = $('#web_blacklist li');		
		var len = lis.length;			
		for(var i=0; i<len;i++){			
			lis[i].remove();
		}
		//传值处同步删除
		document.getElementById("web_blacklistvalue").value ="";
	
	});
 	
 	//初始校验表单
 	if($("#validateForm").html()){
 		$("#validateForm").autovalidate();
 	}
	$(".btn-save").click(function(){
		if (!$("#validateForm").validate()) {
			return false;
		}
		$("#validateForm").submit();
		return false;
	});
	
	
	$(".btn-cancel").click(function(){
		location.href = "../../../zone?page="+$("#page").val();
	});
	
	
	//鼠标划过小图片显示大图片
	 $("#son_imgDiv").mousemove(function(event){
		var event = event || window.event;
		$("#enlarge_images").css("display","block");
		var imgsrc = $(this).find("img#smallImg").attr("src");
		imgsrc = imgsrc.substring(0,imgsrc.lastIndexOf(".")-6)+imgsrc.substring(imgsrc.lastIndexOf("."),imgsrc.length);
		$("#enlarge_images").html('<img src="'+imgsrc+'"/>');
		$("#enlarge_images").css("top",document.body.scrollTop + event.clientY - 300 + "px");
		$("#enlarge_images").css("left",document.body.scrollLeft + event.clientX - 660 + "px");
	});
	$("#son_imgDiv").mouseout(function(event){
		$("#enlarge_images").html("");
		$("#enlarge_images").css("display","none");
	});
	
});

//初始化选择文件框
function initFile(obj,pictureName){
	var name = "";
	if(pictureName == "" || pictureName == null || pictureName == "noFiles"){
		name = "No File ...";
	}else{
		name = pictureName.substring(pictureName.lastIndexOf("\\")+1,pictureName.length);
	}
	obj.ace_file_input({
		no_file:name,
		btn_choose:'选择',
		btn_change:'改变',
		droppable:false,
		onchange:null,
		thumbnail:false
	});
}

//文件上传ajax文件上传
function getUploadFile(){
	var _href = $("#uploadfilestr").attr('href');
	$.ajaxFileUpload({
		url:_href, 
		secureuri:false,
		fileElementId:"uploadfile",
		dataType: 'json',
		success: function (result, status) {
			var path = result.data['url'];
			removeFile("uploadfile","filepicture_picture","uploadfilehidden",result);
			if (result.status == 'ok') {
				var orgImg = path.substring(0,path.indexOf(","));
				var smallImg = path.substring(path.indexOf(",")+1);
				$("#uploadfilehidden").val(orgImg);
				$("#smallImg").attr("src",smallImg);
				$("#default_path_small").val(smallImg);
				$("#imgDivs").css("display","block");
				$("#deletUrl").css("display","inline-block");
				var result = 0;
				removeFile("uploadfile","filepicture_picture","uploadfilehidden",result);
				bootbox.alert("上传成功！");
			}else if (result.status == 'error') {
				$("#uploadfilehidden").val("");
				$("#smallImg").attr("src","");
				$("#default_path_small").val("");
				$("#imgDivs").css("display","none");
				$("#deletUrl").css("display","none");
			    bootbox.alert(result.msg);
			}
		},
		error: function (data, status, e)
		{
			$("#uploadfilehidden").val("");
			$("#smallImg").attr("src","");
			$("#default_path_small").val("");
			$("#imgDivs").css("display","none");
			$("#deletUrl").css("display","none");
			removeFile("uploadfile","filepicture_picture","uploadfilehidden");
			console.log(e);
		}
	});
	return false;
}


//上传文件时conle file 删除 file
function removeFile(_elemId,_removeId,picPathId,result){
	var filename = $('#'+_elemId).parent().find("span").attr("data-title");
	var isChrome = navigator.userAgent.toLowerCase().match(/chrome/) != null;//判断是否是谷歌浏览器
	if(filename==null || filename==''){
		filename = "No File ...";
	}
	var option = {}; 
	var defaultOptions = {
			no_file:'No File ...',
			btn_choose:'选择',
			btn_change:'改变',
			droppable:false,
			onchange:null,
			thumbnail:false
	};
	if(isChrome && result == 0){
		option = {no_file:filename };
	}else if(isChrome && result == 1){
		option = {no_file:'No File ...' };
	}else{
		option = {no_file:filename };
	}
	var opts = $.extend(defaultOptions,option);
	var newfile = $("#"+_elemId).clone();
	$("#"+_removeId).find(".ace-file-input").remove();
	$("#"+_removeId+" #"+picPathId).after(newfile);
	$("#"+_elemId).ace_file_input(opts);
}

function exportExcel_zone(id){
	var searchValue = $("#searchValue").val();
	if(searchValue == "请输入关键字"){
		searchValue = "";
	}
	var param = "?operatorId="+id+"&searchValue="+searchValue;
	$("#exportExcel").attr("href",$("#ctx").val()+"/back/main/zone/exportExcel"+param);
	return false;
}
